package com.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.listener.DictListener;
import com.example.mapper.DictMapper;
import com.example.service.DictService;
import com.example.ylgh.model.cmn.Dict;
import com.example.ylgh.vo.cmn.DictEeVo;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hx
 * @create 2022/5/9 23:04
 * description:
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;
    /**
     * 根据数据id查询子数据列表
     *
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildrenData(Long id) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId, id);
        List<Dict> list = list(queryWrapper);
        for (Dict dict : list) {
            Long dictId = dict.getId();
            boolean ischild = isChildren(dictId);
            dict.setHasChildren(ischild);
        }
        return list;
    }

    //导出excel
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = null;
            fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //查询数据库
            List<Dict> dictList = list();
            ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
            for (Dict dict : dictList ) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVos.add(dictEeVo);
            }
            //调用写的方法
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict").doWrite(dictEeVos);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 导入数据字典进入数据库
     * allEntries = true: 方法调用后清空所有缓存
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，根据value查询
        if (ObjectUtils.isEmpty(dictCode)){
            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dict::getValue,value);
            Dict dict = dictMapper.selectOne(queryWrapper);
            return dict.getName();
        }else {
            //如果dictCode不为空，根据value和parentId查询
            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dict::getDictCode,dictCode);
            //根据dictcode查询id
            Dict dictParent = dictMapper.selectOne(queryWrapper);
            Long id = dictParent.getId();
            Dict dict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id).eq(Dict::getValue, value));
            return dict.getName();

        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode获取id
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictCode,dictCode);
        Dict dict = dictMapper.selectOne(queryWrapper);
        //根据id获取下级节点
        List<Dict> childrenData = findChildrenData(dict.getId());
        return childrenData;
    }

    //判断id下面是否有字节点(是不是父节点)
    private boolean isChildren(Long id) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId, id);
        long count = count(queryWrapper);
        return count > 0;
    }
}
